package saucaca.fragment;

import java.util.ArrayList;
import java.util.List;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;
import saucaca.CustomView.CircularImageView;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Object.MenuObject;
import saucaca.Util.ImageDisplayListener;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

@SuppressLint({ "Recycle", "InflateParams" })
public class MenuFragment extends ListFragment {
	String TAG = MenuFragment.class.getSimpleName();
	ArrayList<MenuObject> listMenu;
	public static final String key_code = "code";
	public static final String key_fragment = "fragment";

	CircularImageView accountAvatar;
	ImageLoader imageLoader = ImageLoader.getInstance();
	TextView txtNameuser;
	DisplayImageOptions options;
	Resources res;
	Context context;
	boolean isOnline = true;
	boolean isLogin = false;
	MainActivity mainActivity;
	public MenuAdapter menuAdapter;
	public Button btnLogin;
	LinearLayout footerChude, footerTheloai, footerCaidat, footerThongtin, footerUngdung, headerTrangchu, headerNct, headerAccount;
	ArrayList<LinearLayout> listMenuLinear;

	public static MenuFragment getInstance(Activity activity) {
		MenuFragment fileViewFragment = new MenuFragment();
		return fileViewFragment;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity=(MainActivity)getActivity();
		context = mainActivity;
		options = new DisplayImageOptions.Builder().showImageOnFail(R.drawable.ic_default).showStubImage(R.drawable.ic_default).showImageForEmptyUri(R.drawable.ic_default)
				.cacheInMemory().cacheOnDisc().build();
		new getService().execute("");
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getListView().setDivider(null);
		getListView().setVerticalScrollBarEnabled(false);
		getListView().setSelector(R.color.transparent);
		res = getResources();
		addHeaderListview();
		initMenu();
		listMenu = new ArrayList<MenuObject>();
		isOnline = false;
		String[] sListmenu = res.getStringArray(R.array.menu_list_string);
		TypedArray menuIcons = res.obtainTypedArray(R.array.menu_list_picture);
		for (int i = 0; i < sListmenu.length; i++) {
			MenuObject menuObject = new MenuObject();
			menuObject.setMenuCode(Integer.toString(i));
			menuObject.setName(sListmenu[i]);
			String indexIcon = Integer.toString(menuIcons.getResourceId(i, 0));
			menuObject.setAvatar(indexIcon);
			listMenu.add(menuObject);
		}
		menuAdapter = new MenuAdapter(getActivity(), listMenu);
		setListAdapter(menuAdapter);
	}

	void initMenu() {
		listMenu = (ArrayList<MenuObject>) HomeData.homeListMENU;
		new getService().execute("");
	}

	private class getService extends AsyncTask<String, Void, String> {
		final String TAG = "JsonReader";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... urls) {
			String str = null;
			str = WServiceLib.getHomeString();
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				try {
					JsonReader.readHomeData(result);
					SetmenuOnline();
				} catch (Exception e) {
					Log.e(TAG, "_____Exception_______:" + e.toString());
					e.printStackTrace();
				}
			}
		}
	}

	public void SetmenuOnline() {
		ArrayList<MenuObject> list = (ArrayList<MenuObject>) HomeData.homeListMENU;
		if (list != null) {
			isOnline = true;
			listMenu = list;
			menuAdapter = new MenuAdapter(getActivity(), listMenu);
			menuAdapter.notifyDataSetChanged();
			setListAdapter(menuAdapter);
		}
	}

	public void addHeaderListview() {
		View convertView = getActivity().getLayoutInflater().inflate(R.layout.menu_header, null);
		btnLogin = (Button) convertView.findViewById(R.id.list_menu_logo_buttonlogin);
		String user = null;
		try {
			user = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (user != null) {
			if (!user.equals("")) {
				btnLogin.setText(mainActivity.getResources().getString(R.string.logout));
				isLogin = true;
			}
		} else
			btnLogin.setText(mainActivity.getResources().getString(R.string.login));
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isLogin) {
					logoutDialog();
				} else {
					String newContent = AccountLoginFragment.class.getName();
					switchFragment(newContent);
				}
			}
		});
		headerTrangchu = (LinearLayout) convertView.findViewById(R.id.header_trangchu);
		headerTrangchu.setOnClickListener(clickListener);

		headerAccount = (LinearLayout) convertView.findViewById(R.id.layout_username);
		headerAccount.setOnClickListener(clickListener);
		accountAvatar = (CircularImageView) convertView.findViewById(R.id.account_avatar);
		txtNameuser = (TextView) convertView.findViewById(R.id.header_account_name);

		String strAvatar = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_avatar);
		String strName = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_fullname);
		if (strAvatar != null) {
			int mExpandOnDragHeight = (int) getResources().getDimension(R.dimen.header_account);
			ViewGroup.LayoutParams params = headerAccount.getLayoutParams();
			params.height = mExpandOnDragHeight;
			Bitmap bitmap = BaseEngine.BitmapFromBase64(strAvatar);
			accountAvatar.setImageBitmap(bitmap);
			txtNameuser.setText(strName);
		}
		headerNct = (LinearLayout) convertView.findViewById(R.id.header_nhaccuatui);
		headerNct.setOnClickListener(clickListener);
		getListView().addHeaderView(convertView, null, false);
		View viewFooter = getActivity().getLayoutInflater().inflate(R.layout.menu_footer, null);
		findviewbyid(viewFooter);
		footerChude.setOnClickListener(clickListener);
		footerTheloai.setOnClickListener(clickListener);
		footerCaidat.setOnClickListener(clickListener);
		footerThongtin.setOnClickListener(clickListener);
		footerUngdung.setOnClickListener(clickListener);

		listMenuLinear = new ArrayList<LinearLayout>();
		listMenuLinear.add(headerTrangchu);
		listMenuLinear.add(headerNct);
		listMenuLinear.add(footerChude);
		listMenuLinear.add(footerTheloai);
		listMenuLinear.add(footerCaidat);
		listMenuLinear.add(footerThongtin);
		listMenuLinear.add(footerUngdung);

		getListView().addFooterView(viewFooter, null, false);
	}

	public void changedLoginstatus(boolean isLoggin) {
		if (isLoggin) {
			btnLogin.setText(getResources().getString(R.string.logout));
			isLogin = isLoggin;
			String strAvatar = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_avatar);
			String strName = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_fullname);
			if (strAvatar != null) {
				int mExpandOnDragHeight = (int) getResources().getDimension(R.dimen.header_account);
				ViewGroup.LayoutParams params = headerAccount.getLayoutParams();
				params.height = mExpandOnDragHeight;
				Bitmap bitmap = BaseEngine.BitmapFromBase64(strAvatar);
				accountAvatar.setImageBitmap(bitmap);
				txtNameuser.setText(strName);
			}
		} else {
			ViewGroup.LayoutParams params = headerAccount.getLayoutParams();
			params.height = 0;
			btnLogin.setText(mainActivity.getResources().getString(R.string.login));
			PreferenceUtils.clear(mainActivity);
			isLogin = false;
		}
	}

	void findviewbyid(View view) {
		footerCaidat = (LinearLayout) view.findViewById(R.id.footer_caidat);
		footerThongtin = (LinearLayout) view.findViewById(R.id.footer_thongtin);
		footerUngdung = (LinearLayout) view.findViewById(R.id.footer_ungdung);
		footerChude = (LinearLayout) view.findViewById(R.id.footer_chude);
		footerTheloai = (LinearLayout) view.findViewById(R.id.footer_theloai);

	}

	private void clearselected() {
		for (int i = 0; i < listMenuLinear.size(); i++) {
			listMenuLinear.get(i).setBackgroundResource(R.drawable.button_menu_background);
		}
	}

	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			clearselected();
			menuAdapter.update(-1);
			String newContent = null;
			switch (v.getId()) {
			case R.id.footer_chude:
				newContent = TopicFragment.class.getName();
				footerChude.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.header_trangchu:
				newContent = home.class.getName();
				headerTrangchu.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.layout_username:
				String type=PreferenceUtils.getString(mainActivity, TagName.KeyPreference_typelogin);
				if(type!=null&& type.equals(TagName.KeyPreference_Account))
					newContent = AccountUpdateInfoFragment.class.getName();
				break;
			case R.id.header_nhaccuatui:
				newContent = LocalAllMusic.class.getName();
				headerNct.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.footer_theloai:
				newContent = CateFragment.class.getName();
				footerTheloai.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.footer_thongtin:
				newContent = InforFragment.class.getName();
				footerThongtin.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.footer_caidat:
				newContent = SettingFragment.class.getName();
				footerCaidat.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			case R.id.footer_ungdung:
				newContent = AppFragment.class.getName();
				footerUngdung.setBackgroundResource(R.drawable.menu_item_pressed_header);
				break;
			}
			if (!BaseEngine.isConnectionAvailable(mainActivity) && newContent != LocalAllMusic.class.getName())
				if (HomeData.homeListMENU == null) {
					newContent = FragmentErrorConnect.class.getName();
				}
			if (newContent != null) {
				switchMenuFragment(newContent);
			}
		}
	};

	public void logoutDialog() {
		AlertDialog builder = new AlertDialog.Builder(mainActivity).create();
		builder.setMessage(mainActivity.getResources().getString(R.string.logout_warning));
		builder.setCancelable(false);
		builder.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				changedLoginstatus(false);
			}
		});
		builder.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		String newContent = null;
		MenuObject menuObject = listMenu.get(position - 1);
		clearselected();
		if (BaseEngine.isConnectionAvailable(mainActivity)) {
			if (menuObject.getMenuCode().equals("0001")) {
				newContent = home.class.getName();
			} else if (menuObject.getMenuCode().equals("0002")) {
				newContent = OnlineSongFragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0003")) {
				newContent = ArtistListfragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0004")) {
				newContent = VideoFragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0005")) {
				newContent = AlbumFragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0006")) {
				newContent = NewFragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0007")) {
				newContent = BXHfragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0008")) {
				newContent = TvShowFragment.class.getName();
			} else if (menuObject.getMenuCode().equals("0009")) {
				newContent = RingtoneFragment.class.getName();
			} else {
				newContent = FragmentErrorConnect.class.getName();
				menuAdapter.update(-1);
			}
			menuAdapter.update(position - 1);
		} else {
			newContent = FragmentErrorConnect.class.getName();
			menuAdapter.update(-1);
		}

		if (newContent != null) {
			switchMenuFragment(newContent);
		}
	}

	void destroyFragment(String fragmentName) {
		Fragment f = null;
		for (int i = 0; i < mainActivity.mFragmentList.size(); i++) {
			if (mainActivity.mFragmentList.get(i).getClass().getName().equals(fragmentName)) {
				f = mainActivity.mFragmentList.get(i);
				FragmentTransaction fragmentTransaction = mainActivity.getSupportFragmentManager().beginTransaction();
				fragmentTransaction.remove(f).commit();
			}
		}
	}

	private void switchMenuFragment(String fragment) {
		if (getActivity() == null)
			return;
		else if (getActivity() instanceof MainActivity) {
			MainActivity a = (MainActivity) getActivity();
			a.mSilidingUP.collapsePanel();
			// a.switchContent(fragment);
			a.menuselect(fragment);

		}
	}

	private void switchFragment(String fragment) {
		if (getActivity() == null)
			return;
		else if (getActivity() instanceof MainActivity) {
			MainActivity a = (MainActivity) getActivity();
			a.mSilidingUP.collapsePanel();
			a.switchContent(fragment);

		}
	}

	public class MenuAdapter extends ArrayAdapter<MenuObject> {
		List<MenuObject> adtlistmenu = null;
		int indexSelected = -1;

		private class ViewHolder {
			ImageView icon;
			TextView title;
			LinearLayout layout;
		}

		public MenuAdapter(Context context, ArrayList<MenuObject> users) {
			super(context, R.layout.item_menu, users);
			adtlistmenu = users;
		}

		public void update(int index) {
			this.indexSelected = index;
			notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			MenuObject user = adtlistmenu.get(position);
			ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				LayoutInflater inflater = LayoutInflater.from(getContext());
				convertView = inflater.inflate(R.layout.item_menu, parent, false);
				viewHolder.layout = (LinearLayout) convertView.findViewById(R.id.list_item_section_layout);
				viewHolder.icon = (ImageView) convertView.findViewById(R.id.list_item_section_imageview);
				viewHolder.title = (TextView) convertView.findViewById(R.id.list_item_section_text);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			if (indexSelected == position) {
				viewHolder.layout.setBackgroundResource(R.drawable.menu_item_pressed);
			} else
				viewHolder.layout.setBackgroundResource(R.drawable.menu_item_nomal);
			if (isOnline) {
				// Picasso.with(getActivity()).load(user.getAvatar()).placeholder(R.drawable.ic_default).error(R.drawable.ic_default).transform(new
				// RoundTransform()).into(viewHolder.icon);
				imageLoader.displayImage(user.getAvatar(), viewHolder.icon, options, null);
				viewHolder.title.setText(user.getName());
			} else {
				viewHolder.icon.setImageResource(Integer.parseInt(user.getAvatar()));
				viewHolder.title.setText(user.getName());
			}
			return convertView;
		}

		public List<MenuObject> getAdapterListMenu() {
			return adtlistmenu;
		}

		public void setAdapterListMenu(List<MenuObject> listmenu) {
			this.adtlistmenu = listmenu;
			this.notifyDataSetChanged();
			isOnline = true;
			for (int i = 0; i < listmenu.size(); i++) {
				Log.e("menu", "getName: " + listmenu.get(i).getName());
				Log.e("menu", "getAvatar: " + listmenu.get(i).getAvatar());
			}

		}
	}

}
